<template>
	<section> 
		<el-form class="toolbar" label-width="120px" style="margin-top:10px;padding-top:20px;">
			<el-row>
				<el-col :span="8">
					<el-form-item label="支付时间">
						<el-date-picker
                              v-model="dateValue"
                              type="daterange"
							  @change="datechange"
							  style="width:100%"
                              range-separator="至"
                              value-format="yyyy-MM-dd"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期">
                        </el-date-picker>
					</el-form-item> 
				</el-col>
				<el-col :span="8">
					<el-form-item label="用户账号">
							<el-input v-model="account"></el-input>
					</el-form-item> 
				</el-col>	
				<el-col :span="8">
					<el-form-item label="平台订单号">
							<el-input v-model="orderId"></el-input>
					</el-form-item> 
				</el-col>
				
				
			</el-row>
			<el-row>
				<el-col :span="8">
					<el-form-item label="第三方订单编号">
							<el-input v-model="orderNum"></el-input>
					</el-form-item> 
				</el-col>
				<el-col :span="6">
					<el-form-item label="分站名称">
						  <el-select v-model="webSiteId" placeholder="请选择">
							<el-option
							v-for="item in fzlist"
							:key="item.id"
							:label="item.name"
							:value="item.id">
							</el-option>
						</el-select>
					</el-form-item> 
				</el-col>	
				<el-col :span="5">
					<el-form-item label="平台筛选">
							<el-select v-model="orignal" placeholder="请选择">
                                    <el-option label="淘宝天猫" value="淘宝天猫"></el-option>
                                    <el-option label="京东" value="京东"></el-option>
                                    <el-option label="拼多多" value="拼多多"></el-option> 
                        </el-select>
					</el-form-item> 
				</el-col>	
				<el-col :span="5">
					<el-form-item label="状态筛选">
						<el-select v-model="state" placeholder="请选择">
                                    <el-option label="未发货" value="0"></el-option>
                                    <el-option label="已发货" value="1"></el-option>
                                </el-select>
					</el-form-item> 
				</el-col>	
			</el-row>
			<el-form-item>
					<el-button type="primary" @click="search">搜索</el-button> 
                    <el-button type="primary" @click="daochu">导出报表</el-button> 
                    <el-button type="primary" @click="uploadDiv=true">上传报表</el-button> 
			</el-form-item>
		</el-form>

		<!--列表-->
	
			<el-table
          :data="tableData"
          border
          @selection-change="handleSelectionChange"
          :header-cell-style="{background:'#f7f7f7'}"
          style="width: 100%">
          <el-table-column
                                            type="selection"
                                            width="55">
                                          </el-table-column>
          <el-table-column
            prop="webSiteName"
            label="分站名称"
            align="center">
          </el-table-column>
		  <el-table-column
            prop="account"
            label="分站账号"
            align="center">
          </el-table-column>
          <el-table-column
            prop="orderCount"
            align="center"
            label="订单数">
          </el-table-column>
          <el-table-column
            align="center"
            label="订单金额">
            <template slot-scope="scope">
                {{scope.row.money/100}} 元
            </template>
          </el-table-column>
          <el-table-column
            prop="payTime"
            align="center"
			width="200"
            label="支付时间">
          </el-table-column>
		  <el-table-column
            prop="orignal"
            align="center"
            label="平台">
          </el-table-column>
          <el-table-column
            prop="state"
            align="center"
            label="任务状态">
             <template slot-scope="scope">
                <span v-if="scope.row.state==0">未发货</span>
                <span v-if="scope.row.state==1">已发货</span>
            </template>
          </el-table-column>
          
          <el-table-column
            label="操作"
            align="center"
            >
            <template slot-scope="scope">
              <el-button size="mini" @click="detailList(scope.row.id);">查看详细订单</el-button> 
            </template>
          </el-table-column>
        </el-table>

		<div style="padding:20px;text-align:center;">
            <el-pagination
            background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>  

	<el-dialog title="查看订单" custom-class="orderMain" :visible.sync="detailDiv">
		<el-row :gutter="15">
                         <el-col :span="4"><el-input v-model="detailForm.id" placeholder="平台订单号"></el-input></el-col>
                         <el-col :span="4"><el-input v-model="detailForm.mobile" placeholder="收件人手机"></el-input></el-col>
                         <el-col :span="4"><el-input v-model="detailForm.orderNum" placeholder="第三方订单号"></el-input></el-col>
                         <!-- <el-col :span="4">
                           <el-select placeholder="快递公司">
                                <el-option label="圆通快递" value="0"></el-option>
                                <el-option label="顺丰快递" value="1"></el-option>
                          </el-select>
                         </el-col> -->
                         <el-col :span="4"><el-input v-model="detailForm.packNum" placeholder="快递单号"></el-input></el-col>
                         <el-col :span="4">
                           <el-date-picker
						    v-model="dateValue"
                              @change="datechange2"
							  placeholder="支付日期"
                              type="daterange"
                              range-separator="至"
                              value-format="yyyy-MM-dd"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期">
                            </el-date-picker>
                         </el-col>
						 <el-col :span="4">
                           <el-select v-model="detailForm.state" placeholder="全部包裹状态">
                                <el-option label="未发货" value="0"></el-option>
                                <el-option label="已发货" value="1"></el-option>
                          </el-select>
                         </el-col>
                     </el-row>  
                     <div style="padding:15px;text-align:center">
                           <el-button @click="search2" type="primary">查询</el-button>
                         </div>  
        <el-table
          :data="tableData2"
          border
		  max-height="250"
          style="width: 100%">
          
          <el-table-column
            prop="orderNum"
			fixed
            label="第三方订单号"
            align="center"
            width="200">
          </el-table-column>
          <el-table-column
            prop="expressCompany"
            align="center"
            label="快递">
          </el-table-column>
          <el-table-column
            prop="packNum"
            align="center"
            label="快递单号">
          </el-table-column>
          <el-table-column
            prop="userName"
            align="center"
            label="收件人姓名">
          </el-table-column>
          <el-table-column
            prop="mobile"
            align="center"
            label="收件人手机">
          </el-table-column>
          <el-table-column
            align="center"
            label="商品费用">
             <template slot-scope="scope">
                {{scope.row.price/100}} 元
             </template>  
          </el-table-column>
          <el-table-column
            align="center"
            label="快递费用">
            <template slot-scope="scope">
                {{scope.row.expressPrice/100}} 元
             </template>  
          </el-table-column>
          <el-table-column
            prop="createTime"
            width="200"
            align="center"
            label="创建时间">
          </el-table-column>
        </el-table>
		<div style="padding:20px;text-align:center;">
            <el-pagination
            background
              @size-change="handleSizeChange2"
              @current-change="handleCurrentChange2"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="size2"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total2">
            </el-pagination>
          </div>  
    </el-dialog>	

		<el-dialog
		title="上传报表"
		:visible.sync="uploadDiv"
		custom-class="upDiv"
		>
			<el-upload
                                    class="upload-demo"
                                    drag
                                    :multiple="false"
                                    :limit=1
                                    :show-file-list="true"
                                    :on-change="importExcel"
                                    :auto-upload="false"
                                    action="/">
                                    <i class="el-icon-upload"></i>
                                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                                  </el-upload>
		<span slot="footer" class="dialog-footer">
			<el-button @click="uploadDiv = false">取 消</el-button>
			<el-button type="primary" @click="uploadDiv = false;uploader()">确 定</el-button>
		</span>
		</el-dialog>
	</section>
</template>
<script>
import XLSX from 'xlsx'
export default {
  data() {
    return {
	dateValue:'',	
	  account:'',
	  webSiteId:'',
	  orderNum:'',
	  orderId:'',
	  state:'',
	  orignal:'',
      page:1,
      size:10,
      total:0,
	  tableData: [],
	  page2:1,
      size2:10,
      total2:0,
	  tableData2: [],
	  fzlist:[],
	  begin:'',
	  end:'',
	  detailDiv:false,
	  uploadDiv:false,
	  taskIds:'',
	   detailForm:{
        id:'',
        taskId:'',
        mobile:'',
        orderNum:'',
        packNum:'',
        state:'',
        begin:'',
        end:''
	  },
	  list:[]
    };
  },
  mounted(){
	this.getfzlist();  
    this.search();
  },
  methods:{
	  datechange(e){
		 this.begin=e.split('至')[0];
		 this.end=e.split('至')[1];
	  },
	   datechange2(e){
		 this.detailForm.begin=e.split('至')[0];
		 this.detailForm.end=e.split('至')[1];
	  },
	getfzlist(){
		let that = this;
      this.axios({
        method: "GET",
        headers: {
          "Authorization": sessionStorage.getItem("token"),
          "Content-Type": "application/x-www-form-urlencoded",
          "domain": "taobao.tianyalei.com"
        },
        url:
          "/webSite?page=0&size=999999&name=&account="
      }).then(function(response) {
        if (response.data.code == 200) {
          that.fzlist = response.data.data.list;
        }
      });
	},
     search(){
      let that = this;
      this.axios
        .get(
          "task?begin="+that.begin+'&end='+that.end+'&state='+that.state+'&page='+(that.page-1)+'&size='+that.size+'&account='+that.account+'&webSiteId='+that.webSiteId+'&orderNum='+that.orderNum+'&orderId='+that.orderId+'&orignal='+that.orignal,
          {
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
              "domain": "taobao.tianyalei.com",
              "Authorization":sessionStorage.getItem('token')
            }
          }
        )
        .then(function(response) {
          if (response.data.code == 200) {
             for(var i=0;i<response.data.data.list.length;i++){
                response.data.data.list[i].payTime=that.gettime(response.data.data.list[i].payTime);
             }
             that.tableData=response.data.data.list;
             that.total=response.data.data.totalCount;
          } 
        });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size=val;
      this.search();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page=val;
      this.search();
	},
	handleSizeChange2(val) {
      console.log(`每页 ${val} 条`);
      this.size2=val;
      this.search2();
    },
    handleCurrentChange2(val) {
      console.log(`当前页: ${val}`);
      this.page2=val;
      this.search2();
    },
    gettime(t){
        var _time=new Date(t);
        var   year=_time.getFullYear();//2017
        var   month=_time.getMonth()>8?(_time.getMonth()+1):'0'+(_time.getMonth()+1);//7
        var   date=_time.getDate()>9?_time.getDate():'0'+_time.getDate();//10
        var   hour=_time.getHours()>9?_time.getHours():'0'+_time.getHours();;//10
        var   minute=_time.getMinutes()>9?_time.getMinutes():'0'+_time.getMinutes();;//56
        var   second=_time.getSeconds()>9?_time.getSeconds():'0'+_time.getSeconds();;//15
        
        return   year+"-"+month+"-"+date+"   "+hour+":"+minute+":"+second;//这里自己按自己需要的格式拼接
	},
	detailList(id){
		this.detailDiv=true;
		this.detailForm.taskId=id;
		this.search2();
	},
	search2(){
		this.detailForm.begin=this.dateValue[0];
        this.detailForm.end=this.dateValue[1];
        this.detailForm.page=this.page2-1;
        this.detailForm.size=this.size2;
		let that=this;
       this.axios
          .get(
            '/order?'+that.qs.stringify(that.detailForm),
            {
              headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "domain": "taobao.tianyalei.com",
                "Authorization":sessionStorage.getItem('token')
              }
            }
          )
          .then(function(response) {
            if (response.data.code == 200) {
              for(var i=0;i<response.data.data.list.length;i++){
                  if(response.data.data.list[i].createTime){
                      response.data.data.list[i].createTime=that.gettime(response.data.data.list[i].createTime);
                  }
              }
              that.tableData2=response.data.data.list;
              that.total2=response.data.data.totalCount;
            } 
          });
	},
    handleSelectionChange(val) {
        console.log(val)
        let arry=[]
        for(var i=0;i<val.length;i++){
            arry.push(val[i].id)
        }
        this.taskIds=arry.join(',');
	  },
	  daochu(){
        let that=this;
        if(this.taskIds==''){
          that.$message({
              message:"请最少勾选一条数据",
              type: 'warning'
           });
           return
        }
        
        this.axios.post('/task/outputExcel',
        this.qs.stringify({taskIds:this.taskIds}),{
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'domain':'taobao.tianyalei.com',
                "Authorization":sessionStorage.getItem('token')
              }
            })
        .then(function (response) {
            if(response.data.code==200){
               let arry=[];
               for (var i=0;i<response.data.data.length;i++){
                  arry.push({
					  分站名称:response.data.data[i].shopName,
                      原始单号:response.data.data[i].orderId,
					  收件人:response.data.data[i].userName,
					  手机:response.data.data[i].mobile,
					  网名:response.data.data[i].buyAccount,
                      地址:response.data.data[i].address,
					  物流公司:response.data.data[i].expressCompany,
					  发货条件:response.data.data[i].condition,
					  商家编码:response.data.data[i].shopCode,
					  货品数量:response.data.data[i].goodsCount,
					  应收合计:response.data.data[i].totalMoney/100,
					  邮费:response.data.data[i].expressMoney/100,
					  优惠金额:response.data.data[i].youhui/100,
					  货品总价:response.data.data[i].goodsMoney/100,
					  订单类别:response.data.data[i].orderType
                  })
               }
               that.JSONToExcelConvertor(arry,'订单列表')
            }else{
                that.$message({
                  message: response.data.message,
                  type: 'warning'
                });
            }
          })
      },
      //json数据转excel
     JSONToExcelConvertor(JSONData, FileName) {  
            //先转化json  
            var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;  
            var excel = '<table border="1"  rull="all" style="border-collapse: collapse">';   
            var row = "<tr>";           
            //设置表头  
            var keys = Object.keys(JSONData[0]);  
            keys.forEach(function (item) {
                row += "<td>" + item + '</td>';
            });     
            //换行  
            excel += row + "</tr>";  
            //设置数据
            for (var i = 0; i < arrData.length; i++) {  
                var row = "<tr>";  
                for (var index in arrData[i]) {  
                    console.log(arrData[i][index]);
                    //var value = arrData[i][index] === "." ? "" : arrData[i][index];  
                    row += '<td>' + arrData[i][index] + '</td>';  
                }  
                excel += row + "</tr>";  
            }  

            excel += "</table>";  

            var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>";  
            excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';  
            excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel';  
            excelFile += '; charset=UTF-8">';  
            excelFile += "<head>";  
            excelFile += "<!--[if gte mso 9]>";  
            excelFile += "<xml>";  
            excelFile += "<x:ExcelWorkbook>";  
            excelFile += "<x:ExcelWorksheets>";  
            excelFile += "<x:ExcelWorksheet>";  
            excelFile += "<x:Name>";  
            excelFile += "{worksheet}";  
            excelFile += "</x:Name>";  
            excelFile += "<x:WorksheetOptions>";  
            excelFile += "<x:DisplayGridlines/>";  
            excelFile += "</x:WorksheetOptions>";  
            excelFile += "</x:ExcelWorksheet>";  
            excelFile += "</x:ExcelWorksheets>";  
            excelFile += "</x:ExcelWorkbook>";  
            excelFile += "</xml>";  
            excelFile += "<![endif]-->";  
            excelFile += "</head>";  
            excelFile += "<body>";  
            excelFile += excel;  
            excelFile += "</body>";  
            excelFile += "</html>";  

            var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile);  

            var link = document.createElement("a");      
            link.href = uri;  

            link.style = "visibility:hidden";  
            link.download = FileName + ".xls";  

            document.body.appendChild(link);  
            link.click();  
            document.body.removeChild(link);  
		},
		sortArr(arr, str) {
    var _arr = [],
        _t = [],
        // 临时的变量
        _tmp;
 
    // 按照特定的参数将数组排序将具有相同值得排在一起
    arr = arr.sort(function(a, b) {
        var s = a[str],
            t = b[str];
 
        return s < t ? -1 : 1;
    });
 
    if ( arr.length ){
        _tmp = arr[0][str];
    }
    // console.log( arr );
    // 将相同类别的对象添加到统一个数组
    for (var i in arr) {
        console.log( _tmp);
        if ( arr[i][str] === _tmp ){
            console.log(_tmp)
            _t.push( arr[i] );
        } else {
            _tmp = arr[i][str];
            _arr.push( _t );
            _t = [arr[i]];
        }
    }
    // 将最后的内容推出新数组
    _arr.push( _t );
    return _arr;
},
     importExcel(evt) {//读取方法
      this.$message({
                  message: '上传成功',
                  type: 'success'
                });
      this.buyList=[];          
     let that=this;
	var wb; //读取完成的数据
	var rABS = false; //是否将文件读取为二进制字符串
	var isCSV;
	if(!evt) {
		return;
	}
	var f = evt.raw;
	var reader = new FileReader();
 
	var pet = new Promise(function(resolve, reject) {
		reader.onload = function(e) {
			var data = e.target.result;
			var XLSX = require('xlsx');
			wb = null;
			if(isCSV) {
				data = new Uint8Array(data);
				let f = that.isUTF8(data);
				//console.log("是CSV文件,编码" + (f ? "是" : "不是") + "UTF-8");
				if(f) {
					data = e.target.result;
				} else {
					var str = cptable.utils.decode(936, data);
					wb = XLSX.read(str, {
						type: "string"
					});
				}
			} else {
				//console.log("不是CSV文件");
			}
			if(!wb) {
				wb = rABS || isCSV ? XLSX.read(btoa(that.fixdata(data)), {
					type: 'base64'
				}) : XLSX.read(data, {
					type: 'binary'
				});
			}
			//console.log(wb);
			//wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
			//wb.Sheets[Sheet名]获取第一个Sheet的数据
			//console.log(JSON.parse(JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])).replace(/\s+/g,"")));
      var result = JSON.parse(JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])).replace(/\s+/g,"").replace(/'/g,''));
      var array=[];
      for(var i=0;i<result.length;i++){
            array.push(
              {
                orderId:result[i].原始单号.toString(),
                expressCompany:result[i].物流公司.toString(),
                packNum:result[i].物流单号.toString()
              }
            )
         }

      that.list=array;
			resolve(result);
		}
		isCSV = f.name.split(".").reverse()[0] == "csv"; //判断是否是 CSV
		if(rABS || isCSV) {
			reader.readAsArrayBuffer(f);
		} else {
			reader.readAsBinaryString(f);
		}
		evt.value = "";
 
	}).catch(error => console.log(error));
	console.log(pet);
	return pet;
},
fixdata(data) { //文件流转BinaryString
	var o = "",
		l = 0,
		w = 10240;
	iconv.skipDecodeWarning = true;
	let str = iconv.encode(o, 'utf-8');
	for(; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
	o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
	return o;
},
isUTF8(bytes) { //非中文格式CSV文件转换UTF-8方法
	var i = 0;
	while(i < bytes.length) {
		if(( // ASCII
				bytes[i] == 0x09 ||
				bytes[i] == 0x0A ||
				bytes[i] == 0x0D ||
				(0x20 <= bytes[i] && bytes[i] <= 0x7E)
			)) {
			i += 1;
			continue;
		}
		if(( // non-overlong 2-byte
				(0xC2 <= bytes[i] && bytes[i] <= 0xDF) &&
				(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF)
			)) {
			i += 2;
			continue;
		}
		if(( // excluding overlongs
				bytes[i] == 0xE0 &&
				(0xA0 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
				(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)
			) ||
			( // straight 3-byte
				((0xE1 <= bytes[i] && bytes[i] <= 0xEC) ||
					bytes[i] == 0xEE ||
					bytes[i] == 0xEF) &&
				(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
				(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)
			) ||
			( // excluding surrogates
				bytes[i] == 0xED &&
				(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0x9F) &&
				(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF)
			)
		) {
			i += 3;
			continue;
		}
		if(( // planes 1-3
				bytes[i] == 0xF0 &&
				(0x90 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
				(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
				(0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
			) ||
			( // planes 4-15
				(0xF1 <= bytes[i] && bytes[i] <= 0xF3) &&
				(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0xBF) &&
				(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
				(0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
			) ||
			( // plane 16
				bytes[i] == 0xF4 &&
				(0x80 <= bytes[i + 1] && bytes[i + 1] <= 0x8F) &&
				(0x80 <= bytes[i + 2] && bytes[i + 2] <= 0xBF) &&
				(0x80 <= bytes[i + 3] && bytes[i + 3] <= 0xBF)
			)
		) {
			i += 4;
			continue;
		}
		return false;
	}
	return true;
},
	uploader(){
		let that=this; 
					this.axios.post('/task/inputExcel', 
					{
						list:this.list
					}, 
					{
						headers: {
							'Authorization':sessionStorage.getItem("token"),
							'Content-Type':'application/json',
							'domain':'taobao.tianyalei.com'
						}
        })
    .then(function (response) {
       if(response.data.code==200){   
              that.$message({
                message:'导入成功',
                type: 'success'
				}); 
			  that.uploadDiv=false;
			  that.search();
          }
     }) 
	}
  }
};
</script>
<style>
.orderMain {width:90%;}
.upDiv {width:400px!important;}
</style>